package com.csxy.m2020_note.sql;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.csxy.m2020_note.Notebean;

import java.util.ArrayList;
import java.util.List;

//封装好的一个数据库访问类
/*
NoteDbHelper notedb=new NoteDbHelper(Activity.this);

notedb.open();
int a=notedb.createNote("标题","内容");
//关闭数据库
notedb.close();

 */
public class NoteDbHelper {

    private String LOGTAG="NoteDbHelper";
    private static final String DB_NAME = "data1";
    private static final int DB_VERSION = 1;

    private static final String TABLE_NAME = "notes";
    private static final String KEY_TITLE = "title";
    private static final String KEY_BODY = "body";
    private static final String KEY_ROWID = "_id";

    private Context ctx = null;
    private NoteSQLiteHelper dbHelper = null;
    private SQLiteDatabase db = null;

    //构造函数


    public NoteDbHelper(Context ctx) {

        this.ctx = ctx;

    }

   public NoteDbHelper open(){
        dbHelper=new NoteSQLiteHelper(ctx,DB_NAME,null,DB_VERSION);
        db=dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        dbHelper.close();
    }

    public int createNote(String title,String body){
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, title);
        values.put(KEY_BODY, body);
        int rowId = (int)db.insert(TABLE_NAME, null, values);
        return rowId;

    }

    public boolean updateNote(long rowId, String title, String body) {
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, title);
        values.put(KEY_BODY, body);

        int updatedRows = db.update(TABLE_NAME, values, KEY_ROWID + "=" + rowId, null);
        //int updatedRows受影响的行  正常来说就是
        boolean result=updatedRows > 0;

       // return updatedRows > 0;
        return result;
    }

    public boolean deleteNote(long rowId) {
        int deletedRows = db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null);
        return deletedRows > 0;
    }

    public List<Notebean> getAllNotes()
    {
        //获取游标
        Cursor c=db.query(TABLE_NAME, null,
                null, null, null, null, null);

        //初始化集合
        ArrayList<Notebean> itemList = new ArrayList<Notebean>();
        // c.moveToNext()游标指向下一行
        while (c.moveToNext()) {

            Notebean item = new Notebean();
            //c.getColumnIndex(KEY_ROWID)根据列名获取该列的索引
            //c.getInt(index)根据索引获取数据
            item.setId(c.getInt(c.getColumnIndex(KEY_ROWID)));
            item.setTitle(c.getString(c.getColumnIndex(KEY_TITLE)));
            item.setBody(c.getString(c.getColumnIndex(KEY_BODY)));

            Log.v(LOGTAG, "Notebean-" + item.toString());
            //添加数据
            itemList.add(item);

        }
        return itemList;

    }




}


